from typing import List


class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        m = len(grid)
        if not m:
            return 0
        n = len(grid[0])

        def in_area(x, y):
            return x < m and y < n

        island = b = 0

        for x in range(m):
            for y in range(n):
                if grid[x][y] == 0:
                    continue

                if in_area(x + 1, y) and grid[x + 1][y] == 1:
                    b += 1
                if in_area(x, y + 1) and grid[x][y + 1] == 1:
                    b += 1
                island += 1
        print(island, b)
        return island * 4 - 2 * b

